// stock/stock_balance/stock_balance.js
let listBehavior = require('../../behavior/list')

Page({
  behaviors: [ listBehavior, ],

  /**
   * 页面的初始数据
   */
  data: {
    list: [],

    //搜索商品
    keyList: [
      {field_id: 'goods_id',field_name: '商品编码'},
      {field_id: 'goods_name',field_name: '商品名称'}
      ],
    //快速搜索
    searchList: [
      {field_id: 'date',type: 'dateonly',field_name: '库存日期',dfltdate: wx.$util.formatDate(new Date(),'yyyy-MM-dd')},
      {field_id: 'quote_Warehouse',type: 'reference1',mainEntity: 'Warehouse',showFields: 'warehouse_name',field_name: '仓库',optionList: [],optionName: 'warehouse_name',optionId: 'row_id'}
    ],
    //提交搜索数据
    searchObj: {
      date: wx.$util.formatDate(new Date(),'yyyy-MM-dd'),
      good_list: '',
      is_zero_show: '',
      quote_Warehouse: ''
    },
    goodsList: [],  //商品列表

    displayField: [ //显示字段
      {field: 'goods_type_name',title: '商品类别'},
      {field: 'goods_model_name',title: '规格'},
      {field: 'goods_unit_name',title: '单位'},
    ],
    subDisplayField: [],  //明细显示字段
    //合计
    sumList: [
      {name: '单位数量',num: 0},
      {name: '成本小计',num: 0}
      ],
  },
  //展开收起仓库
  toggleShow(e){
    let index = e.currentTarget.dataset.index;
    this.setData({[`list[${index}].isOpen`]: !this.data.list[index].isOpen})
  },
  //显示零库存商品
  onRadioChange(e){
    this.setData({
      ['searchObj.is_zero_show']: e.detail
    });
    this.getFirstPage();
  },

  //搜索数据
  searchData(e){
    let {detail} = e,
      {goodsList,searchObj} = this.data;
    let good_list = [],
      quote_Warehouse = [];

    //输入框搜商品
    if (detail.iptVal){
      wx.$each(goodsList,(i,item)=>{
        if (item.goods_id.indexOf(detail.iptVal) >= 0 || item.goods_name.indexOf(detail.iptVal) >= 0){
          good_list.push(item.row_id);
        }
      });
    }
    //快速查询
    wx.$each(detail.quick,(i,item)=>{
      searchObj[item.CompareWith] = item.CompareValue;
    });

    searchObj.good_list = good_list.join(',');
    this.setData({searchObj});
    this.getFirstPage();

  },

  //跳转页面
  navTo(e){
    let url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url
    })
  },

  //合计数据
  sumData(data){
    let {sumList} = this.data,
      key = ['全部仓库_balance_quantity','全部仓库_balance_price'],
      sum = [0,0];
    wx.$each(data,(i,item)=>{
      sum[0] = parseFloat((sum[0] + item[key[0]]).toFixed(2));
      sum[1] = parseFloat((sum[1] + item[key[1]]).toFixed(2));
    });
    sumList[0].num = sum[0];
    sumList[1].num = sum[1];
    this.setData({sumList});
  },

  getDataList(){
    let {searchObj} = this.data;
    wx.$post(1,'Stock/query_goods_inout_details_balance',searchObj).then(res=>{
      if (res.errcode != 0)return;
      let data = res.data.row || [];
      this.getSCol(res.data.sum);
      this.setData({ list: data,page:1,total: data.length,limit: data.length});

      this.sumData(data);
    })
  },
  getSCol(field){
    let nameArr = [],
      fieldList = [];
    wx.$each(field,(i,item)=>{
      let arr = item.field_name && item.field_name.split('|');
      if (arr && arr[1]){
        let name = arr[0],
          index = nameArr.indexOf(name),
          fieldObj = {field: item.field_id,title: arr[1]};
        if (index < 0){
          nameArr.push(name);
          fieldList.push({ title: name, fields: [fieldObj] ,isAll: name === '全部仓库'});
          return
        }
        fieldList[index].fields.push(fieldObj);
      }
    });
    this.setData({subDisplayField: fieldList})
  },


  //获取下拉选项
  getOptionsList(arg){
    let [key,v,url,post,iseach,parse] = arg;
    return new Promise((resolve,reject) => {
      wx.$post(v, url, post).then(res=>{
        if (res.errcode != 0){
          reject();
          return;
        }
        let data = res.data.row || [],
          list = data;
        if (iseach){
          list = this.eachData(data,'row_id',parse);
        }
        resolve({[key]: list});
      });
    });
  },
  ready(options){

    let parmaArr = [
        ['good_list',3,'DynamicQuery/query_dynamic_v1',{"oby": "goods.row_id desc","table_id": "goods","page":1,"limit":0}],  //商品
        ['quote_Warehouse',3,'DynamicQuery/query_dynamic_v1',{"oby": "Warehouse.row_id desc","table_id": "Warehouse","page":1,"limit":0}],  //仓库
      ],
      pmArr = [];
    this.getOptionsList(parmaArr[0]).then(res=>{
      this.data.goodsList = res.good_list;
    })
    this.getOptionsList(parmaArr[1]).then(res=>{
      this.setData({ [`searchList[1].optionList`]: res.quote_Warehouse });
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$setBarTitle();
    this.getDataList();
    this.ready();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
